/**
 * 
 */
package br.com.cotec.security.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;

import br.com.cotec.security.User;

/**
 * @author Magalhaes
 *
 */
@Repository("userDao")
public class UserDaoHibernate implements UserDao, UserDetailsService {

	/**
     * Log variable for all child classes. Uses LogFactory.getLog(getClass()) from Commons Logging
     */
    protected final Log log = LogFactory.getLog(getClass());
	
	@PersistenceContext
	private EntityManager em;
	
    /**
     * Constructor that sets the entity to Users.class.
     */
    public UserDaoHibernate() {
        super();
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public List<User> getUsers() {
    	Query q = em.createQuery("FROM User u order by upper(u.username)");
    	return q.getResultList();
        //return getHibernateTemplate().find("from Users u order by upper(u.username)");
    }

    /**
     * {@inheritDoc}
     */
    public User saveUser(User user) {
        if (log.isDebugEnabled())
            log.debug("user's id: " + user.getId());
        em.persist(user);
        //getHibernateTemplate().saveOrUpdate(user);
        // necessary to throw a DataIntegrityViolation and catch it in UserManager
        //getHibernateTemplate().flush();
        em.flush();
        return user;
    }

    /** 
     * {@inheritDoc}
    */
    @SuppressWarnings("unchecked")
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    	Query q = em.createQuery("FROM User u WHERE u.username LIKE :pUser");
    	q.setParameter("pUser", username);
        List users = q.getResultList(); 
        	//getHibernateTemplate().find("from Users where username=?", username);
        if (users == null || users.isEmpty()) {
            throw new UsernameNotFoundException("user '" + username + "' not found...");
        } else {
            return (UserDetails) users.get(0);
        }
    }

    /** 
     * {@inheritDoc}
    *
    public String getUserPassword(String username) {
        SimpleJdbcTemplate jdbcTemplate =
                new SimpleJdbcTemplate(SessionFactoryUtils.getDataSource(getSessionFactory()));
        Table table = AnnotationUtils.findAnnotation(Users.class, Table.class);
        return jdbcTemplate.queryForObject(
                "select password from " + table.name() + " where username=?", String.class, username);

    }*/
    
}